package com.wolfking.converter.transform.base;


import com.wolfking.converter.transform.FieldTransform;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.Objects;

@Slf4j
public class EnumFieldTransform implements FieldTransform<Enum<?>> {


    @Override
    public boolean canTransform(Class<?> fieldType) {
        return fieldType.isEnum();
    }

    @Override
    public Enum<?> transform(Object value) {
        throw new UnsupportedOperationException();
    }

    @Override
    @SuppressWarnings("all")
    public Enum<?> transform(Class<?> fieldType, Object value) throws Exception {
        if (!fieldType.isEnum()) {
            return null;
        }
        if (Objects.isNull(value)) {
            return null;
        }
        String toStr = value.toString();
        if (StringUtils.isBlank(toStr)) {
            return null;
        }
        try {
            Enum<?>[] enumConstants = ((Class<Enum<?>>) fieldType).getEnumConstants();
            for (Enum<?> enu : enumConstants) {
                if (enu.name().equalsIgnoreCase(toStr)) {
                    return enu;
                }
            }
        } catch (Exception e) {
            log.warn("", e);
        }
        return null;
    }
}
